//
//  ZHCacheFoundation.m
//  ToolsEnginer
//
//  Created by 正合适 on 2017/6/1.
//  Copyright © 2017年 正合适. All rights reserved.
//

#import "ZHCacheFoundation.h"
#import "FMDB.h"

#define kTableName  NSStringFromClass([self class]) // 表名

@interface ZHCacheFoundation ()
/**数据库*/
@property (nonatomic, strong) FMDatabase *db;

@end

@implementation ZHCacheFoundation

#pragma mark - ---------- private method ----------
#pragma mark - 单例
+ (instancetype)instance {
    static ZHCacheFoundation *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ZHCacheFoundation alloc] initWithDataBaseName:[ZHCacheFoundation dbName]];
    });
    return instance;
}

#pragma mark - 初始化数据库
- (instancetype)initWithDataBaseName:(NSString *)dbName {
    self = [super init];
    if (self) {
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *file = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"ZH_%@.sqlite", dbName]];
        _db = [FMDatabase databaseWithPath:file];
        if ([_db open]) {
            NSLog(@"---------- 数据库：%@ 创建并打开成功 ----------",dbName);
        } else {
            NSLog(@"---------- 数据库：%@ 创建并打开失败 ----------",dbName);
        }
    }
    return self;
}

#pragma mark - 数据库名
+ (NSString *)dbName {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *executableFile = [infoDictionary objectForKey:(NSString *)kCFBundleExecutableKey]; //获取项目名称
    return executableFile;
}

#pragma mark - 创建表
- (BOOL)createTable:(NSString *)tableName {
    BOOL result = NO;
    if ([_db open]) {
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS T_%@ (key text primary key, jsonval text not null);",tableName];
        result = [_db executeUpdate:sql];
    }
    if (result) {
        NSLog(@"---------- ZHCommonCache数据库：Table_%@ 表创建成功 ----------",tableName);
    } else {
        NSLog(@"---------- ZHCommonCache数据库：Table_%@ 表创建失败 ----------",tableName);
    }
    return NO;
}

#pragma mark - ---------- public method ----------
#pragma mark - 判断是否已有key
- (BOOL)isKey:(NSString *)key table:(NSString *)tableName {
    if (key.length == 0 || tableName.length == 0) return YES;
    if (![self createTable:tableName]) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM T_%@ WHERE key=?;",tableName];
        FMResultSet *resultSet = [_db executeQuery:sql, key];
        if ([resultSet next]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return YES;
    }
}

#pragma mark - 增
- (BOOL)insertWithVal:(NSString *)val key:(NSString *)key table:(NSString *)tableName {
    BOOL result = NO;
    if ([val isKindOfClass:[NSNull class]]) {
        val = @"";
    }
    if (key.length == 0 || tableName.length == 0) {
        NSLog(@"---------- ZHCommonCache数据库：参数错误，insert失败 ----------");
        result = NO;
    } else {
        if (![self createTable:tableName]) {
            NSLog(@"---------- ZHCommonCache数据库：插入value：%@ ----------",val);
            NSString *sql = [NSString stringWithFormat:@"INSERT INTO T_%@(key, jsonval) VALUES(?,?);",tableName];
            result = [_db executeUpdate:sql,key, val];
        }
    }
    return result;
}

#pragma mark - 改
- (BOOL)updateWithVal:(NSString *)val key:(NSString *)key table:(NSString *)tableName {
    BOOL result = NO;
    if ([val isKindOfClass:[NSNull class]]) {
        val = @"";
    }
    if (key.length == 0 || tableName.length == 0) {
        NSLog(@"---------- ZHCommonCache数据库：参数错误，update失败 ----------");
        result = NO;
    } else {
        if (![self createTable:tableName]) {
            NSLog(@"---------- ZHCommonCache数据库：更新value：%@ ----------",val);
            NSString *sql = [NSString stringWithFormat:@"UPDATE T_%@ SET jsonval=? WHERE key=?;",tableName];
            result = [_db executeUpdate:sql, val, key];
        }
    }
    return result;
}

#pragma mark - 查
- (NSString *)selectWithKey:(NSString *)key table:(NSString *)tableName {
    NSString *result = nil;
    if (key.length == 0 || tableName.length == 0) {
        NSLog(@"---------- ZHCommonCache数据库：参数错误，select失败 ----------");
        result = nil;
    } else {
        if (![self createTable:tableName]) {
            NSString *sql = [NSString stringWithFormat:@"SELECT jsonval FROM T_%@ WHERE key=?;",tableName];
            FMResultSet *resultSet = [_db executeQuery:sql, key];
            if ([resultSet next]) {
                result = [resultSet objectForColumnIndex:0];
            }
        }
    }
    NSLog(@"---------- ZHCommonCache数据库：查找value：%@ ----------",result);
    return result;
}

#pragma mark - 删
- (BOOL)deleteWithKey:(NSString *)key table:(NSString *)tableName {
    if (key.length == 0 || tableName.length == 0) return NO;
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM T_%@ WHERE key=?;",tableName];
    return [_db executeUpdate:sql,key];
}

#pragma mark - 清空表
- (BOOL)clearTable:(NSString *)tableName {
    if (tableName.length == 0) return NO;
    NSString *sql = [NSString stringWithFormat:@"DROP TABLE IF EXISTS T_%@",tableName];
    return [_db executeUpdate:sql];
}

@end
